﻿using System.Web.Mvc;
using ML.Entity;
using ML.IBusiness;

namespace ML.WebApi.Controllers
{
    /// <summary>
    /// 用户邀请
    /// </summary>
    [CrossSite]
    public class UserInvitationController : BaseApiController
    {

        private readonly IUserInvitationBusiness userInvitationBusiness;
        private readonly IUserBusiness userBusiness;
        private readonly IInvitationProfitBusiness invitationProfitBusiness;

        public UserInvitationController(IUserInvitationBusiness _userInvitationBusiness, IUserBusiness _userBusiness, IInvitationProfitBusiness _invitationProfitBusiness)
        {
            this.userInvitationBusiness = _userInvitationBusiness;
            this.userBusiness = _userBusiness;
            this.invitationProfitBusiness = _invitationProfitBusiness;
        }

        /// <summary>
        /// 添加用户邀请信息(如果已经有对应信息就不添加)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("api/userInvitation/add")]
        [HttpPost]
        public BaseResult<bool> Add(UserInvitationModel model)
        {
            //根据邀请码转换邀请id
            model.InvitationId = userBusiness.GetByInvitationCode(model.InvitationId).data.Id;
            //邀请人不能自己邀请自己，每个被邀请的用户只能被邀请一次
            if (model.InvitationId==model.BeInvitationId)
            {
                return new BaseResult<bool>(200,"你不能邀请自己",false);
            }
            var isTrue = userInvitationBusiness.CheckAlreadyInvited(model.InvitationId, model.BeInvitationId).data;
            if (!isTrue)
            {
                var entity = new UserInvitationEntity { AddType = model.AddType, BeInvitationId = model.BeInvitationId, ContentSource = model.ContentSource, InvitationId = model.InvitationId };
                if (userInvitationBusiness.Add(entity).data)
                {
                  return  invitationProfitBusiness.Add(new InvitationProfitEntity {InvitationCount = 1,SuccessCount = 0,UserId = model.InvitationId});
                }
            }
            else
            {
                return new BaseResult<bool>(200, "该用户不能被邀请", false);
            }
            return new BaseResult<bool>(false);
        }
    }
}